package com.archermind.boc.utils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

public class UtilsTools {

	final static CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();

	public static IoBuffer getIoBuffer(String xml)
			throws CharacterCodingException {
		IoBuffer ioBuffer = null;
		try {
			ioBuffer = IoBuffer.allocate(6);
			ioBuffer.setAutoExpand(true);
			ioBuffer.putString(xml, encoder);
			ioBuffer.flip();
		} catch (Exception e) {
			System.out.println("[ ddddddddddddddddddd ]");
			e.printStackTrace();
		}
		return ioBuffer;
	}

	public static Long getIdFromSessionId(String sessionId) {
		String id = null;
		try {
			id = sessionId.split("-")[1];
		} catch (Exception e) {
			return null;
		}

		return new Long(id);
	}

	public static String getIPFromSessionId(String sessionId) {
		return sessionId.split("-")[0];
	}

	public static String getSessionID(IoSession session) {
		String sessionID = session.getRemoteAddress().toString();
		sessionID = sessionID.substring(1, sessionID.indexOf(":"));
		sessionID = sessionID + "-" + session.getId();
		return sessionID;
	}

	public static String dateToStr(Date date) {
		String dateTime = "";
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss sss");
		// TimeZone timeZone = TimeZone.getTimeZone("UTC");
		// dateFormat.setTimeZone(timeZone);
		if (date != null) {
			dateTime = dateFormat.format(date);
		}
		return dateTime;
	}

	public static String getLocalIP() throws Exception {
		String addr = "";
		InetAddress address = null;
		NetworkInterface net = null;
		Enumeration<InetAddress> inetAddress = null;
		Enumeration<NetworkInterface> network = NetworkInterface
				.getNetworkInterfaces();
		while (network.hasMoreElements()) {
			net = network.nextElement();
			inetAddress = net.getInetAddresses();
			while (inetAddress.hasMoreElements()) {
				address = inetAddress.nextElement();
				if (address instanceof Inet6Address) {
					continue; // omit IPv6 address
				}
				addr = address.getHostAddress();
			}
		}
		return addr;
	}
}
